package com.hunsy.d2d.mqtt.netty.server.netty;

import com.hunsy.d2d.mqtt.netty.handler.http.HttpInitializer;
import com.hunsy.d2d.mqtt.netty.handler.tcp.TcpInitializer;
import com.hunsy.d2d.mqtt.netty.server.Server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Created by hunsy on 2017/5/2.
 */
public class NettyServer implements Server {

    private static Logger logger = LoggerFactory.getLogger(NettyServer.class);

//    private final int port = ConfigService.getIntProperty("tcp.port", 1883);
//    private final int httpPort = ConfigService
//            .getIntProperty("http.port", 8080);

    private Properties properties;

    private List<Channel> channels = new ArrayList<Channel>();
    private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

    public NettyServer() {
//        properties = PropKit.use("mqtt.properties").getProperties();
        init();
    }

    /**
     * 初始化Netty Server
     */
    private void init(){
        logger.info("\n");
        logger.info("开始初始化NettyServer");
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup)
                .option(ChannelOption.SO_BACKLOG, 1000)
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        try {
            server.childHandler(new TcpInitializer()).bind(properties.getProperty("tcp.port"),1883).sync();
            server.childHandler(new HttpInitializer()).bind(properties.getProperty("http.port"),3000).sync();
//            server.
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }


    public void start() {

    }

    public void destroy() {

    }
}
